package org.hyjiacan.deadqq.server.db;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.hyjiacan.deadqq.common.entity.User;


public class DBUtil {

	private static final Properties db = new Properties();
	private static Connection connection;

	static {

		try {
			db.load(DBUtil.class.getResourceAsStream("db.properties"));
			Class.forName(getString("driver"));
			connection = DriverManager.getConnection(getString("url"),
					getString("user"), getString("pswd"));
		} catch (IOException ex) {
			Logger.getLogger(DBUtil.class.getName())
					.log(Level.SEVERE, null, ex);
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static Connection getConnection() {
		return connection;
	}

	public static Statement getStatement() {
		try {
			return connection.createStatement();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public static PreparedStatement getPreparedStatement(String sql) {
		try {
			return connection.prepareStatement(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	public static void closeConnection() {
		try {
			if (!connection.isClosed()) {
				connection.close();
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String getString(String key) {
		return db.getProperty(key.toLowerCase());
	}

	public static User getUser(ResultSet rs) throws SQLException {

		User u = new User();
		u.setAge(rs.getInt(getString("age")));
		u.setAvatar(rs.getString(getString("avatar")));
		u.setBirthday(rs.getDate(getString("birthday")));
		u.setId(rs.getInt(getString("uid")));
		u.setLevel(rs.getInt(getString("level")));
		u.setMale(rs.getBoolean(getString("gender")));
		u.setName(rs.getString(getString("realname")));
		u.setNickname(rs.getString(getString("nickname")));
		u.setNumber(rs.getLong(getString("number")));
		u.setOnline(rs.getBoolean(getString("isonline")));
		u.setPassword(rs.getString(getString("password")));
		u.setRegdate(rs.getDate(getString("regdate")));
		u.setSignature(rs.getString(getString("signature")));

		return u;
	}

	public static List<User> getUsers(ResultSet rs) throws SQLException {
		List<User> list = new ArrayList<User>();
		while (rs.next()) {
			list.add(getUser(rs));
		}
		return list;
	}
}
